package com.toman.ui.work.device;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.InputType;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.LinearLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.lzy.okhttputils.request.PostRequest;
import com.toman.Enum.BaseEnum;
import com.toman.Enum.NetworkEnum;
import com.toman.Enum.PermEnum;
import com.toman.Enum.TimeEnum;
import com.toman.Enum.ViewTypeEnum;
import com.toman.Interfaces.NewBaseUrl;
import com.toman.JavaBean.PreMaintenanceRecordEntity;
import com.toman.JavaBean.WarmUpConfigEntity;
import com.toman.R;
import com.toman.Util.JsonUtils;
import com.toman.Util.SPUtils;
import com.toman.Util.ToastUtil;
import com.toman.Util.ViewUtil;
import com.toman.bean.ItemListBean;
import com.toman.bean.TemplateInfBean;
import com.toman.bean.TemplateInfBeanPreHandler;
import com.toman.camera.Camera;
import com.toman.templateActivity.controler.TempInfAdapter;
import com.toman.toolbar.ToolBarActivity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by 邹苏隆 on 2018/11/5.
 * description：
 */
public class PreviewHotConfigInfActivity extends ToolBarActivity {
    @BindView(R.id.ll)
    LinearLayout ll;
    private TempInfAdapter adapter;
    List<TemplateInfBean> list = new ArrayList<>();
    WarmUpConfigEntity bean;
    Camera camera;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_problem_feedback_inf);
        setContentView(R.layout.layout_template_inf);

        ButterKnife.bind(this);
        initIntent();
        initView();


    }

    private void initIntent() {
        bean = (WarmUpConfigEntity) getIntent().getSerializableExtra("bean");
        status = getIntent().getStringExtra("status");
    }

    private void initView() {
        baseEnum=BaseEnum.PREVIEWHOTCONFIG;
                initToolBar(baseEnum.detail());

        List<ItemListBean> type = new ArrayList<>();
        type.add(new ItemListBean(
                "产线", "1"));
        type.add(new ItemListBean("设备", "2"));
        String typeName="";
        if (bean.getWarmUpType()==1){
            typeName="产线";
        }
        if (bean.getWarmUpType()==2){
            typeName="设备";
        }
        TemplateInfBean depBean =new TemplateInfBean("departmentId", "部门名称", bean.getDepartmentName(), bean.getDepartmentId(), ViewTypeEnum.CLICK, NetworkEnum.DEP, mCompanyId, false, true,true);
        TemplateInfBean typeBean = new TemplateInfBean("warmUpType", "预热类型", typeName, bean.getWarmUpType()+"", ViewTypeEnum.CLICK, type, false, true, true);
        TemplateInfBean beletBean = new TemplateInfBean("beltlineId", "产线名称", bean.getBeltlineName(), bean.getBeltlineId(), ViewTypeEnum.MUTICLICK, NetworkEnum.BELTLINE, mCompanyId, false, true, true){
            @Override
            public void doAction(TemplateInfBean observable,TemplateInfBean listener) {
                if (observable==typeBean){
                    if (observable.getResult().equals("1")){
                        listener.setName("beltlineId");
                        listener.setResult(null);
                        listener.setContent(null);
                        listener.setTitle("产线名称");
                        listener.setNetwork(NetworkEnum.BELTLINE);
                        adapter.refresh(list);
                    }

                    else if(observable.getResult().equals("2")){
                        listener.setName("deviceId");
                        listener.setResult(null);
                        listener.setContent(null);
                        listener.setTitle("设备名称");
                        listener.setNetwork(NetworkEnum.DEVICE);
                        adapter.refresh(list);
                    }
                }
                else  if (observable==depBean){

                    Map map =  listener.getMap();
                    map.put("departmentId",observable.getResult());
                    listener.setMap(map);
                    adapter.refresh(list);
                }
            }
        };

        list.add(depBean);
        list.add(typeBean);
        list.add(beletBean);
        list.add(new TemplateInfBean("startTime", "预热开始时间", bean.getStartTime(), bean.getStartTime(), ViewTypeEnum.DATE,TimeEnum.TIME, false, true,true ));
        list.add(new TemplateInfBean("endTime", "预热结束时间", bean.getEndTime(), bean.getEndTime(), ViewTypeEnum.DATE,TimeEnum.TIME, false, true,true ));
        list.add(new TemplateInfBean(null, "创建人", bean.getCreateUserName(), null, ViewTypeEnum.TEXT, true, false,false));
        list.add(new TemplateInfBean(null, "创建时间", bean.getCreateTime(), null, ViewTypeEnum.TEXT, false, false,false));
        list.add(new TemplateInfBean(null, "修改人", bean.getUpdateUserName(), null, ViewTypeEnum.TEXT, false, false,false));
        list.add(new TemplateInfBean(null, "修改时间", bean.getUpdateTime(), null, ViewTypeEnum.TEXT, false, false,false));

        if (bean.getWarmUpType()==2){
            beletBean.setName("deviceId");
            beletBean.setContent(bean.getDeviceName());
            beletBean.setResult(bean.getDeviceId());
            beletBean.setTitle("设备名称");
            beletBean.setNetwork(NetworkEnum.DEVICE);

        }

        beletBean.getMap().put("departmentId",bean.getDepartmentId());
        beletBean.getPreHandlers().add(() -> {
            if(beletBean.getMap()!=null){
                if( beletBean.getMap().get("departmentId")==null){
                    ToastUtil.makeText(getApplicationContext(),"请先选择部门");
                    return false;

                }
            }
            return true;
        });
        typeBean.getListeners().add(beletBean);
        depBean.getListeners().add(beletBean);

        if (status.equals("0")){
            adapter = new TempInfAdapter(list, this, ll,false);
        }
        if (status.equals("1")){
            list.add(new TemplateInfBean(null, "审核人", bean.getAuditUserName(), null, ViewTypeEnum.TEXT, true, false,false));
            list.add(new TemplateInfBean(null, "审核时间", bean.getAuditTime(), null, ViewTypeEnum.TEXT, false, false,false));

            adapter = new TempInfAdapter(list, this, ll,false);
        }


//        camera = list.get(6).getCamera();

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        camera.onActivityResult(requestCode, resultCode, data);
    }

//    @Override
//    public boolean onCreateOptionsMenu(Menu menu) {
//        // Inflate the menu; this adds items to the action bar if it is present.
//        getMenuInflater().inflate(R.menu.toolbar_edit, menu);
//
//
//        MenuItem menuItem = menu.findItem(R.id.menu_edit);
////        还没配置权限
////        if (status.equals("3")|| !SPUtils.contains(getApplicationContext(), BaseEnum.FEEDBACK.has(PermEnum.EDIT))) {
////            menuItem.setVisible(false);
////        }
//        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
//
//            @Override
//            public boolean onMenuItemClick(MenuItem item) {
//                switch (item.getItemId()) {
//                    case R.id.menu_edit:
////                        if (item.getTitle().equals("编辑")) {
////                            item.setTitle("完成");
////                            adapter.edit(true);
////                            camera = list.get(6).getCamera();
////                        } else {
////                            item.setTitle("编辑");
////                            adapter.edit(false);
////                            camera = list.get(6).getCamera();
////
////                        }
//                        break;
//                }
//                return false;
//            }
//        });
//
//        return true;
//    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.toolbar_edit, menu);


        MenuItem menuItem = menu.findItem(R.id.menu_edit);
//        还没配置权限
        if ( !SPUtils.contains(getApplicationContext(), baseEnum.has(PermEnum.EDIT))) {
            menuItem.setVisible(false);
        }
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {

            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.menu_edit:
                        if (item.getTitle().equals("编辑")) {
                            item.setTitle("完成");
                            adapter.edit(true);
                        } else {
                            add();
                        }

                        break;
                }
                return false;
            }
        });

        return true;
    }

    public void add() {

        if (dialog != null) {
            dialog.dismiss();
        }
       if (adapter.isNull()){return;};
        Map<String, Object> map = new HashMap<String, Object>();

        for (TemplateInfBean bean :list){
            if (bean.getName()!=null&&bean.getType()!=ViewTypeEnum.PHOTO){
                map.put(bean.getName(),bean.getResult());
            }
        }
        map.put("id",bean.getId());

        String str = JsonUtils.obj2JsonString(map);

        PostRequest request = OkHttpUtils
                .post(NewBaseUrl.management_warmupterminalconfig_update)
                .headers("token", this.token)
                .postJson(str);



              request  .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", baseEnum.name+": " + result);

                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");ViewUtil.lagout(code,getApplicationContext());

                        if (code == 0) {
                            ToastUtil.makeText(getApplicationContext(), jsonObj.getString("msg"));
//                            ToastUtil.makeText(getApplicationContext(),"获取wifi信号强度成功，状态约30s后会更新");
                            finish();


                        } else {
                            ToastUtil.error(getApplicationContext(), jsonObj.getString("msg"));
                        }

                    }
                });
    }


}
